package cn.zzuisa.deutsch.controller;


import cn.zzuisa.deutsch.base.PageRequest;
import cn.zzuisa.deutsch.base.R;
import cn.zzuisa.deutsch.entity.Article;
import cn.zzuisa.deutsch.entity.Member;
import cn.zzuisa.deutsch.log.annotation.BussinessLog;
import cn.zzuisa.deutsch.service.ArticleService;
import cn.zzuisa.deutsch.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author frank
 * @since 2019-05-07
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    MemberService memberService;

    @GetMapping("/table1")
    public R<Map<String,Object>> recentSevenData1() {
        List<Integer> count = new ArrayList<>();
        List<LocalDate> days = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\tDATE_FORMAT( a.join_time, '%Y-%m-%d' ) days,\n" +
                "\tcount( * ) count \n" +
                "FROM\n" +
                "\t( SELECT * FROM member WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( join_time ) ) AS a \n" +
                "GROUP BY\n" +
                "\tdays", rs -> {
            Map<String,Object> map = new HashMap<>();
            days.add(rs.getDate("days").toLocalDate());
            count.add(rs.getInt("count"));
        });
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("days",days);
        return R.success(map);
    }

    @GetMapping("/table")
    public R<Map<String,Object>> recentSevenData() {
        List<Integer> count = new ArrayList<>();
        List<LocalDate> days = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\tDATE_FORMAT( a.publish_time, '%Y-%m-%d' ) days,\n" +
                "\tcount( * ) count \n" +
                "FROM\n" +
                "\t( SELECT * FROM zzu_article WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( publish_time ) ) AS a \n" +
                "GROUP BY\n" +
                "\tdays", rs -> {
            Map<String,Object> map = new HashMap<>();
            days.add(rs.getDate("days").toLocalDate());
            count.add(rs.getInt("count"));

        });
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("days",days);
        return R.success(map);
    }

    // 近七天发帖数量最多的人
    @GetMapping("/table2")
    public R<List<Map<String,Object>>> table2() {
        final List<Map<String,Object>> list = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\ta.member_id,\n" +
                "\tcount( * ) count ,\n" +
                "\tb.head_img,\n" +
                "\tb.experience,\n" +
                "\tb.`level`,\n" +
                "\tb.signature,\n" +
                "\tb.name,\n" +
                "\tc.config_value\n" +
                "FROM\n" +
                "\t( SELECT * FROM zzu_article WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( publish_time ) ) AS a \n" +
                "\tLEFT JOIN member b ON a.member_id=b.id\n" +
                "\tLEFT JOIN zzu_config c on b.`level` = c.config_name\n" +
                "GROUP BY\n" +
                "\tmember_id\n" +
                "\t",rs->{
            Map<String,Object> map = new HashMap<>();
            map.put("memberId",rs.getLong("member_id"));
            map.put("count",rs.getInt("count"));
            map.put("headImg",rs.getString("head_img"));
            map.put("experience",rs.getInt("experience"));
            map.put("level",rs.getInt("level"));
            map.put("signature",rs.getString("signature"));
            map.put("name",rs.getString("name"));
            map.put("configValue",rs.getString("config_value"));
            list.add(map);
        });
        List<Map<String,Object>> list1 = list.size() > 5 ? list.subList(0,5) : list.subList(0,list.size());
        return R.success(list1);
    }

    // 添加文章
    @PostMapping("add")
    public R<Article> add(@RequestBody Article article, HttpServletRequest request) {
        article.setMemberId(new Long(1));
        article.setPublishTime(LocalDateTime.now());
        articleService.save(article);
        return R.success(article);
    }

    @PutMapping("top")
    public R<String> top(@RequestBody Long[] ids) {
        if(ids == null) {
            return R.error("参数空");
        }
        Arrays.stream(ids).forEach(item -> {
            Article article = articleService.getById(item);
            article.setIsTop(1);
            articleService.updateById(article);
        });
        return R.success("已置顶");
    }

    @PutMapping("untop")
    public R<String> untop(@RequestBody Long[] ids) {
        if(ids == null) {
            return R.error("参数空");
        }
        Arrays.stream(ids).forEach(item -> {
            Article article = articleService.getById(item);
            article.setIsTop(0);
            articleService.updateById(article);
        });
        return R.success("已取消置顶");
    }



    // 分页查询所有文章
    @GetMapping("/page")
    public R<IPage<Map<String,Object>>> page(PageRequest pageRequest, Article article) {
        IPage<Map<String, Object>> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize());
        IPage<Map<String,Object>> articles = articleService.pageByEntity(page,article);
        return R.success(articles);
    }

    // 我发的文章的数量
    @GetMapping("/count")
    public R<Long> countMe(HttpServletRequest request) {
        R<Long> r = new R<>(articleService.count(
                new QueryWrapper<Article>().
                        eq("member_id",request.getSession().getAttribute("member"))));
        return r;
    }
    // 查询看某个文章详情
    @BussinessLog("查看文章：#")
    @GetMapping("/detail/{id}")
    public R<Map<String, Object>> article(@PathVariable String id, @RequestParam(defaultValue = "德语简历注意事项") String title, @RequestParam(required = false) String type,@RequestParam(required = false) String share, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            Member member = (Member) session.getAttribute("member");
            member.setExperience(member.getExperience() + 1).setLevel(member.getExperience()/100+1);
            memberService.updateById(member);

        } catch (Exception e) {
            System.out.println("未登录");
        }

        Map<String, Object> map = null;
        Long aid = null;
        try {
            aid = Long.parseLong(id);
        } catch (NumberFormatException e) {
            aid =1l;
        }
        map = articleService.showArticleById(Long.parseLong(id));
        Article article = articleService.getById(id);
        article.setAssessTimes(article.getAssessTimes() + 1);
        articleService.updateById(article);
        return R.success(map);
    }

    @Data
    static class ArticleUpdate {
        private Long id;
        private String title;
        private String content;
    }
    // 修改文章后返回修改后的内容
    @PutMapping("article")
    public R<Map<String,Object>> update(@RequestBody ArticleUpdate articleUpdate) {
        Article article = articleService.getById(articleUpdate.id);
        article.setContent(articleUpdate.content);
        article.setTitle(articleUpdate.title);
        articleService.updateById(article);
        return R.success(articleService.showArticleById(articleUpdate.id));
    }

}
